// SendKeysOverload.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "SendKeysOverload.h"
#include "SendKeys.h"
#include <shellapi.h>
#include <mmsystem.h>  // mciSendString()

#pragma comment(lib,"winmm.lib")

#define MAX_LOADSTRING 100

// Global Variables:
HINSTANCE	hInst;								// current instance
TCHAR		szTitle[MAX_LOADSTRING];					// The title bar text
TCHAR		szWindowClass[MAX_LOADSTRING];			// the main window class name
CSendKeys	sk;
HWND		hWndOK;
TCHAR		buf[80] = _T("Redirecting keys to Overkill.");
TCHAR		key[20];
int			len = _tcslen(buf);
HFONT		def_font;
COLORREF	def_color;
HWND		hNotepad;
BOOL		bKeyPressed = FALSE;
int			iAppType = 0;
HFONT		hFont = CreateFont(16,                        // nHeight
						 0,                         // nWidth
						 0,                         // nEscapement
						 0,                         // nOrientation
						 FW_HEAVY,                  // nWeight
						 FALSE,                     // bItalic
						 FALSE,                     // bUnderline
						 0,                         // cStrikeOut
						 ANSI_CHARSET,              // nCharSet
						 OUT_DEFAULT_PRECIS,        // nOutPrecision
						 CLIP_DEFAULT_PRECIS,       // nClipPrecision
						 DEFAULT_QUALITY,           // nQuality
						 DEFAULT_PITCH | FF_SWISS,  // nPitchAndFamily
						 _T("Arial"));                 // lpszFacename


// Forward declarations of functions included in this code module:
ATOM				MyRegisterClass(HINSTANCE hInstance);
BOOL				InitInstance(HINSTANCE, int);
LRESULT CALLBACK	WndProc(HWND, UINT, WPARAM, LPARAM);

typedef struct tagApplication
{
	TCHAR sClassName[40];
	TCHAR sWindowName[40];
	TCHAR sExecutable[80];
} Application;

Application app1 =
{
	_T("ConsoleWindowClass"),
	_T("Overkill"),
	_T("D:\\honnunx\\LabView\\MotorControl\\MotorControlTest.exe")
};

Application app2 =
{
	_T("ConsoleWindowClass"),
	_T("Overkill"),
	_T("D:\\honnunx\\LabView\\MotorControl\\RoverProject.exe")
};

BOOL PlayResource(TCHAR *lpName)
{ 
	BOOL bRtn; 
	LPSTR lpRes; 
	HRSRC hResInfo, hRes; 

	// Find the WAVE resource. 

	hResInfo = FindResource(hInst, lpName, _T("WAVE")); 
	if (hResInfo == NULL) 
		return FALSE; 

	// Load the WAVE resource. 

	hRes = (HRSRC) LoadResource(hInst, hResInfo); 
	if (hRes == NULL) 
		return FALSE; 

	// Lock the WAVE resource and play it. 

	lpRes = (LPSTR) LockResource(hRes); 
	if (lpRes != NULL) { 
		bRtn = sndPlaySound((LPCTSTR) lpRes, SND_MEMORY | SND_SYNC | SND_NODEFAULT); 
		UnlockResource(hRes); 
	} 
	else 
		bRtn = 0; 

	// Free the WAVE resource and return success or failure. 

	FreeResource(hRes); 
	return bRtn; 
}

int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);

 	// TODO: Place code here.
	MSG msg;
	HACCEL hAccelTable;

	// Initialize global strings
	LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
	LoadString(hInstance, IDC_SENDKEYSOVERLOAD, szWindowClass, MAX_LOADSTRING);
	MyRegisterClass(hInstance);

	// Perform application initialization:
	if (!InitInstance (hInstance, nCmdShow))
	{
		return FALSE;
	}

	hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_SENDKEYSOVERLOAD));

	// Main message loop:
	while (GetMessage(&msg, NULL, 0, 0))
	{
		if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

	return (int) msg.wParam;
}

//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
//  COMMENTS:
//
//    This function and its usage are only necessary if you want this code
//    to be compatible with Win32 systems prior to the 'RegisterClassEx'
//    function that was added to Windows 95. It is important to call this function
//    so that the application will get 'well formed' small icons associated
//    with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);

	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= LoadIcon(hInstance, MAKEINTRESOURCE(IDI_SENDKEYSOVERLOAD));
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= MAKEINTRESOURCE(IDC_SENDKEYSOVERLOAD);
	wcex.lpszClassName	= szWindowClass;
	wcex.hIconSm		= LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

	return RegisterClassEx(&wcex);
}

//
//   FUNCTION: InitInstance(HINSTANCE, int)
//
//   PURPOSE: Saves instance handle and creates main window
//
//   COMMENTS:
//
//        In this function, we save the instance handle in a global variable and
//        create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
	HWND hWnd;

	hInst = hInstance; // Store instance handle in our global variable

	hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, 1078, 622, 200, 150, NULL, NULL, hInstance, NULL);

	if (!hWnd)
	{
		return FALSE;
	}

	ShowWindow(hWnd, nCmdShow);
	UpdateWindow(hWnd);

	return TRUE;
}

//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;

	if (IsWindowVisible(hWnd) && iAppType > 0)
	{
		if (iAppType == 1)
		{
			hNotepad = FindWindow(app1.sClassName, app1.sWindowName);
			if (! hNotepad)
			{
				PostQuitMessage(0);
			}
		}
		else if (iAppType == 2)
		{
			hNotepad = FindWindow(app2.sClassName, app2.sWindowName);
			if (! hNotepad)
			{
				PostQuitMessage(0);
			}
		}
	}

	switch (message)
	{
		case WM_COMMAND:	wmId    = LOWORD(wParam);
							wmEvent = HIWORD(wParam);
							// Parse the menu selections:
							switch (wmId)
							{
							case IDM_EXIT:
								DestroyWindow(hWnd);
								break;
							default:
								return DefWindowProc(hWnd, message, wParam, lParam);
							}
							break;

		case WM_PAINT:		hdc = BeginPaint(hWnd, &ps);
							def_font = (HFONT) SelectObject(hdc, hFont);
							def_color = SetTextColor(hdc, RGB(255,0,0));
							TextOut(hdc, 0, 0, buf, len);
							SetTextColor(hdc, def_color);
							SelectObject(hdc, def_font);
							EndPaint(hWnd, &ps);
							break;

		case WM_DESTROY:	PostQuitMessage(0);
							break;

		case WM_KEYDOWN:	hWndOK = ::FindWindow(_T("ConsoleWindowClass"), _T("Overkill"));
							if (hWndOK)
							{
								switch (wParam)
								{
									case VK_ESCAPE:	_tcscpy(key, _T("{ESCAPE}")); bKeyPressed = TRUE; break;
									case VK_DELETE:	_tcscpy(key, _T("{DELETE}")); bKeyPressed = TRUE; break;

									case VK_UP:		_tcscpy(key, _T("{UP}")); bKeyPressed = TRUE; break;
									case VK_DOWN:	_tcscpy(key, _T("{DOWN}")); bKeyPressed = TRUE; break;
									case VK_LEFT:	_tcscpy(key, _T("{F6}")); bKeyPressed = TRUE; break;
													// _tcscpy(key, _T("{LEFT}")); break;
									case VK_RIGHT:	_tcscpy(key, _T("{RIGHT}")); bKeyPressed = TRUE; break;

									case VK_F1:		_tcscpy(key, _T("{F5}")); bKeyPressed = TRUE; break;
													// _tcscpy(key, _T("{F1}")); break;
									case VK_F2:		_tcscpy(key, _T("{F2}")); bKeyPressed = TRUE; break;
									case VK_F3:		_tcscpy(key, _T("{F3}")); bKeyPressed = TRUE; break;
									case VK_F4:		_tcscpy(key, _T("{F4}")); bKeyPressed = TRUE; break;
								}
								if (bKeyPressed && iAppType > 0)
								{
									CSendKeys sk;
									sk.AppActivate(hWndOK);
									sk.SendKeys(key);
									Sleep(10);
									SetForegroundWindow(hWnd);
									bKeyPressed = FALSE;
								}
							}
							else
							{
								switch (wParam)
								{
									case VK_F5:		if (iAppType == 0)
													{
														// PlaySound(_T("carstart.wav"), NULL, SND_FILENAME | SND_ASYNC);
														// PlayResource(_T("WAVE1"));
														ShellExecute(hWnd, _T("open"), app1.sExecutable, 0, 0, SW_SHOWNORMAL);
														Sleep(2000);
														iAppType = 1;
													} break;

									case VK_F6:		if (iAppType == 0)
													{
														// PlaySound(_T("carstart2.wav"), NULL, SND_FILENAME | SND_ASYNC);
														// PlayResource(_T("WAVE2"));
														ShellExecute(hWnd, _T("open"), app2.sExecutable, 0, 0, SW_SHOWNORMAL);
														Sleep(2000);
														iAppType = 2;
													} break;
								}
							} break;

		default:			return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}